//
//  HNCategoryViewController.m
//  shezhan
//
//  Created by 朱传正 on 2016/10/27.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNCategoryViewController.h"
#import "HNConcernController.h"
#import "HNConcernController.h"
#import "AppConfig.h"
#define KWidth self.view.frame.size.width

@interface HNCategoryViewController ()

@property (nonatomic,assign)CGFloat contentBrandHeight;
@property (nonatomic,strong)UIView *brandListView;
@property (nonatomic,strong)NSArray *brandHotDataSource;
@property (nonatomic,strong)NSArray *brandListDataSource;
@property (nonatomic,strong)NSString *brandFristName;

@property (nonatomic,assign)CGFloat contentCategoryHeight;
@property (nonatomic,strong)NSArray *categoryDataSource;

@end

@implementation HNCategoryViewController

-(UIView *)brandListView{
    if (!_brandListView) {
         _brandListView = [[UIView alloc]initWithFrame:CGRectMake(0, _contentBrandHeight, KWidth, 0)];
        [self.contentBrandView addSubview:_brandListView];
    }
    return _brandListView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _contentBrandHeight = 0;
    _contentCategoryHeight = 10;
    _contentBrandView.backgroundColor = [UIColor whiteColor];
    _contentCategoryView.backgroundColor = [UIColor whiteColor];
    float colorNum = 114;
    _brandBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _brandBtn.tintColor = RGB(colorNum, colorNum, colorNum);
    _brandBtn.titleLabel.textColor = RGB(colorNum, colorNum, colorNum);
//    _brandBtn.titleLabel.tintColor = RGB(colorNum, colorNum, colorNum);
    
    _categoryBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _categoryBtn.tintColor = RGB(colorNum, colorNum, colorNum);
    _categoryBtn.titleLabel.textColor = RGB(colorNum, colorNum, colorNum);
    _categoryBtn.titleLabel.tintColor = RGB(colorNum, colorNum, colorNum);
    _leftLine.backgroundColor = RGB(colorNum, colorNum, colorNum);
    _rightLine.backgroundColor = RGB(colorNum, colorNum, colorNum);
    
    [self.headLine setHidden:YES];
    [self changeSwitchState:0];//初始切换状态
    //设置Brand刷新
    [self refreshBrandHeadDate];//加载头数据

    //设置分类刷新
    [self refreshCategoryDate];
    //上拉刷新
//    MJRefreshGifHeader *header = [[MJRefreshGifHeader alloc]init];
//    [header setRefreshingBlock:^(void){
//        //        [self refreshHeadDataSource];
//    }];
//    _contentBrandView.mj_header = header;
//    //下拉刷新
//    _contentBrandView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^(void){
//       
//    }];
}

/*返回*/
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/*切换按钮*/
- (IBAction)switchAction:(UIButton *)sender {
    NSInteger i = sender.tag;
    [self changeSwitchState:i];//改变切换状态
}

/*改变切换状态*/
- (void)changeSwitchState:(NSInteger)num{
    switch (num) {
        case 0:
            [self.leftLine setHidden:NO];
            [self.rightLine setHidden:YES];
            [self.contentBrandView setHidden:NO];
            [self.contentCategoryView setHidden:YES];
            [self.headLine setHidden:YES];
            break;
        case 1:
            [self.leftLine setHidden:YES];
            [self.rightLine setHidden:NO];
            [self.contentBrandView setHidden:YES];
            [self.contentCategoryView setHidden:NO];
             [self.headLine setHidden:NO];
            break;
        default:
            break;
    }
}

#pragma mark - Brand页面布局
-(void)createBrandHead:(NSArray *)hotArr{
    self.brandHotDataSource = hotArr;
    NSInteger num = hotArr.count;
    for (int x = 0; x < num; x ++) {
        NSDictionary *goodsDic = hotArr[x];
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, _contentBrandHeight, KWidth, KWidth*3/7 + 65)];
        [self.contentBrandView addSubview:headView];
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, KWidth, KWidth*3/7)];
        
        NSString *goodsImageStr = [NSString stringWithFormat:@"%@%@",url_Base_no,[goodsDic objectForKey:@"hnBrandImg"]];
        if ([AppConfig isNULL:goodsImageStr]) {
              [imageView setImage:[UIImage imageNamed:@"categoryHead"]];
        }else{
              [imageView sd_setImageWithURL:[NSURL URLWithString:goodsImageStr] placeholderImage:[UIImage imageNamed:@"categoryHead"]];
        }
        [headView addSubview:imageView];
        //添加名称
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(imageView.frame.origin.x,imageView.frame.origin.y+imageView.frame.size.height/2-37,imageView.frame.size.width,25)];
        nameLabel.numberOfLines = 1;
        nameLabel.font = [UIFont fontWithName:@"" size:21.0f];
        nameLabel.textColor = [UIColor whiteColor];
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.text = [NSString stringWithFormat:@"%@",[goodsDic objectForKey:@"hnBrandName"]];
        [headView addSubview:nameLabel];
        
        //下边线
        CGSize size = [nameLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:nameLabel.font,NSFontAttributeName, nil]];
        CGFloat lineLabelW = size.width + 4;//名字的宽
        UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(KWidth/2-lineLabelW/2,imageView.frame.origin.y+imageView.frame.size.height/2-9,lineLabelW,1)];
        lineLabel.backgroundColor = [UIColor whiteColor];
        [headView addSubview:lineLabel];
        
        //查看全部
        CGFloat borderViewW = 90;//名字的宽
        UIView *borderView = [[UIView alloc]initWithFrame:CGRectMake(KWidth/2-borderViewW/2,imageView.frame.origin.y+imageView.frame.size.height/2,borderViewW,30)];
        borderView.backgroundColor = RGBA(255, 255, 255, 0);
        borderView.layer.borderWidth = 1;
        borderView.layer.borderColor = [UIColor whiteColor].CGColor;
        [headView addSubview:borderView];
        
        UILabel *desLabel = [[UILabel alloc]initWithFrame:CGRectMake(borderView.frame.origin.x,borderView.frame.origin.y+borderView.frame.size.height/2-8,borderView.frame.size.width,16)];
        desLabel.numberOfLines = 1;
//        desLabel.backgroundColor = [UIColor redColor];
        desLabel.font = [UIFont systemFontOfSize:14];
        desLabel.textColor = [UIColor whiteColor];
        desLabel.textAlignment = NSTextAlignmentCenter;
        desLabel.text = @"查看全部";
        [headView addSubview:desLabel];
        
        
        
        //添加图片点击按钮
        UIButton *imageBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [imageBtn setTitle:@"" forState:UIControlStateNormal];
        [imageBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [imageBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        imageBtn.tag = x;
        imageBtn.frame = imageView.frame;//大小和位置
        [imageBtn addTarget:self action:@selector(enterBrandGoodsList:) forControlEvents:UIControlEventTouchUpInside];
        [headView addSubview:imageBtn];
        
        UIView *btnsView = [[UIView alloc]initWithFrame:CGRectMake(0, imageView.frame.size.height, KWidth, headView.frame.size.height - imageView.frame.size.height)];
        [headView addSubview:btnsView];
        int btnNum = 4;
        CGFloat gap = 15;
        CGFloat leftLength = 40;
        CGFloat btnWidth = (KWidth - 2*leftLength)/4;
        for  (int y = 0; y < btnNum ;y ++) {
            //添加点击按钮
            UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            clickBtn.frame = CGRectMake(leftLength + y*btnWidth, gap, btnWidth, btnsView.frame.size.height - 2*gap);
            [clickBtn setTitle:@"服饰" forState:UIControlStateNormal];
            [clickBtn setFont:[UIFont systemFontOfSize:15]];
            [clickBtn setBackgroundColor:[UIColor whiteColor]];
            [clickBtn setTitleColor:RGB(104, 104, 104) forState:UIControlStateNormal];
            clickBtn.tag = (y+1)*10000 + x;
            [clickBtn addTarget:self action:@selector(enterBrandGoodsList:) forControlEvents:UIControlEventTouchUpInside];
            [btnsView addSubview:clickBtn];
        }
        
        //设置列表高度
        _contentBrandHeight = _contentBrandHeight + headView.frame.size.height;
        //最后一行加载后再改变scrollView高度
        _contentBrandView.contentSize = CGSizeMake(KWidth, _contentBrandHeight);
    }
    //加载列表数据
    [_contentBrandView addSubview:_brandListView];
    [self refreshBrandListDate];
}

-(void)createBrandListView:(NSArray *)goodsData{
    _brandListDataSource = goodsData;
    NSInteger num = goodsData.count;
    CGFloat gl = 25;
    for (NSInteger x = 0; x < num; x ++) {
        NSDictionary *goodsDic = goodsData[x];
        NSString *brandFristName = [NSString stringWithFormat:@"%@",[goodsDic objectForKey:@"hnBrandFristName"]];
        if (self.brandFristName == nil || ![self.brandFristName isEqualToString:brandFristName]) {
            self.brandFristName = brandFristName;
            //首字母显示
            UILabel *headLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, self.brandListView.frame.size.height, KWidth, gl)];
            headLabel.numberOfLines = 1;
            headLabel.font = [UIFont systemFontOfSize:13];
            headLabel.textColor = RGB(82, 82, 82);
            headLabel.textAlignment = NSTextAlignmentCenter;
            headLabel.text = brandFristName;
            headLabel.backgroundColor = RGB(244, 244, 244);
            //        nameLabel.text = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"hnTitle"]];
            [self.brandListView addSubview:headLabel];
            
            CGRect listFrame = self.brandListView.frame;
            listFrame.size.height = listFrame.size.height + headLabel.frame.size.height;
            self.brandListView.frame = listFrame;
        }
     
        
        UIView *rowView = [[UIView alloc]initWithFrame:CGRectMake(0, self.brandListView.frame.size.height, KWidth,80)];
        [self.brandListView addSubview:rowView];
        
        //上边线
        UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, - 1, KWidth, 1)];
        lineLabel.backgroundColor = RGB(242, 241, 242);
        [rowView addSubview:lineLabel];
        //商品图
        CGFloat goodsImageHeight = rowView.frame.size.height - 2*gl;
        UIImageView *goodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, gl, goodsImageHeight*3, goodsImageHeight)];
        
        NSString *goodsImageStr = [NSString stringWithFormat:@"%@%@",url_Base_no,[goodsDic objectForKey:@"hnBrandImg"]];
        [goodsImageView sd_setImageWithURL:[NSURL URLWithString:goodsImageStr] placeholderImage:[UIImage imageNamed:@"goodsImage.png"]];
        //        goodsImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:goodsImageStr]]];
        [rowView addSubview:goodsImageView];
        //商品名
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(gl*2 + goodsImageView.frame.size.width, gl, KWidth - gl*3 - 40 - goodsImageView.frame.size.width, goodsImageHeight)];
        nameLabel.numberOfLines = 1;
        nameLabel.font = [UIFont systemFontOfSize:13];
        nameLabel.textColor = RGB(82, 82, 82);
        nameLabel.textAlignment = NSTextAlignmentLeft;
        nameLabel.text = [NSString stringWithFormat:@"%@",[goodsDic objectForKey:@"hnBrandName"]];
//        nameLabel.text = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"hnTitle"]];
        [rowView addSubview:nameLabel];
        
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.tag = x + 60000;
        clickBtn.frame = rowView.frame;//大小和位置
        [clickBtn addTarget:self action:@selector(enterGoodsListView:) forControlEvents:UIControlEventTouchUpInside];
        [self.brandListView addSubview:clickBtn];
        
        CGRect listFrame = self.brandListView.frame;
        listFrame.size.height = listFrame.size.height + rowView.frame.size.height;
        self.brandListView.frame = listFrame;
    }
    _contentBrandHeight = _contentBrandHeight + self.brandListView.frame.size.height;
    _contentBrandView.contentSize = CGSizeMake(KWidth, _contentBrandHeight);
}

#pragma mark - Category页面布局


-(void)createCategoryView:(NSArray *)categoryArr{
    
    
    CGFloat bl = 12;//border边距
    CGFloat gl = 6;//gap间隙
//    NSInteger num = self.goodsDataSource.count;
    NSInteger num = categoryArr.count;

    for (NSInteger i = 0; i < num; i++) {
        NSDictionary *goodsDataDic  = categoryArr[i];
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake((KWidth/2 - bl/2) * !(i%2 == 0) + bl, _contentCategoryHeight, KWidth/2, KWidth/3)];
        [self.contentCategoryView addSubview:itemView];
        //商品图
        UIImageView *goodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, gl , KWidth/2 - bl*3/2, itemView.frame.size.height - 2*gl)];
        
        NSURL *goodsImageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base_no,[goodsDataDic objectForKey:@"head"]]];
        if ([AppConfig isNULL:goodsImageUrl]) {
            [goodsImageView setImage:[UIImage imageNamed:@"categoryleft"]];
        }else{
                [goodsImageView sd_setImageWithURL:goodsImageUrl placeholderImage:[UIImage imageNamed:@"categoryleft.png"]];
        }
  
        //        goodsImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:goodsImageStr]]];
        [itemView addSubview:goodsImageView];
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, goodsImageView.frame.size.height/2 - 10, goodsImageView.frame.size.width, 20)];
        nameLabel.textColor = [UIColor whiteColor];
        nameLabel.font = [UIFont systemFontOfSize:19];
        nameLabel.numberOfLines = 1;
        nameLabel.textAlignment = NSTextAlignmentCenter;
        nameLabel.text = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"hnTypeName"]];
        [goodsImageView addSubview:nameLabel];
        
        //添加点击按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.tag = i + 10000;
        clickBtn.frame = goodsImageView.frame;//大小和位置
        [clickBtn addTarget:self action:@selector(enterCategoryGoodsDetail:) forControlEvents:UIControlEventTouchUpInside];
        [itemView addSubview:clickBtn];
        
        //设置列表高度
        if (i%2 == 1 || (i + 1 == num && num%2 == 1)) {
            //设置列表高度
            _contentCategoryHeight = _contentCategoryHeight + itemView.frame.size.height;
            //最后一行加载后再改变scrollView高度
            if(i + 1 == num){
                _contentCategoryView.contentSize = CGSizeMake(self.view.frame.size.width, _contentCategoryHeight);
            }
        }
    }
//    self.goodsDataCount = self.goodsDataSource.count;
}




#pragma mark - 品牌 Action
-(void)enterBrandGoodsList:(UIButton *)btn{
    NSLog(@"%ld",btn.tag);
    NSInteger num = btn.tag;
    if (num < 9999) {
        [self pushNextVC:num];
    }else if (num < 19999){
       [self pushNextVC:num-10000];
    }else if (num < 29999){
           [self pushNextVC:num-20000];
    }else if (num < 39999){
           [self pushNextVC:num-30000];
    }else if (num < 49999){
           [self pushNextVC:num-40000];
    }else{
        NSLog(@"-----无此方法-----");
    }
   
}
//进入下一个页面
-(void)pushNextVC:(NSInteger)num{
    NSDictionary *goodsDic = _brandHotDataSource[num];
    HNConcernController *concernVC = [[HNConcernController alloc]init];
    concernVC.hnBrandId = [NSString stringWithFormat:@"%@",[goodsDic objectForKey:@"hnBrandId"]];
    [self.navigationController pushViewController:concernVC animated:YES];
}

-(void)enterGoodsListView:(UIButton *)btn{
    NSInteger num = btn.tag - 60000;
    NSDictionary *goodsDic = _brandListDataSource[num];
    HNConcernController *concernVC = [[HNConcernController alloc]init];
    concernVC.hnBrandId = [NSString stringWithFormat:@"%@",[goodsDic objectForKey:@"hnBrandId"]];
    [self.navigationController pushViewController:concernVC animated:YES];
}




#pragma mark - 分类 Action
-(void)enterCategoryGoodsDetail:(UIButton *)btn{
      NSLog(@"%ld",btn.tag);
    
     NSDictionary *goodsDic = self.categoryDataSource[btn.tag - 10000];
    NSLog(@"goodsDic = %@",goodsDic);
    
    HNConcernController *concernVC = [[HNConcernController alloc]init];
    concernVC.typeId = [goodsDic objectForKey:@"hnTypeId"];
    [self.navigationController pushViewController:concernVC animated:YES];
}


#pragma mark - 刷新品牌数据
-(void)refreshBrandHeadDate{
    //    NSString * loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
    //    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
    //    NSLog(@"==param:%@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_BrandHotBrand parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取详情失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *goodsData = [data objectForKey:@"data"];
            NSLog(@"------goodsData = %@",goodsData);
            //获取所有图片数据数据
            [self createBrandHead:goodsData];
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取详情失败"];
    }];
    
}


-(void)refreshBrandListDate{
//    NSString * loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
//    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
//    NSLog(@"==param:%@",param);

    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_BrandAllOfBrand parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取详情失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *goodsData = [data objectForKey:@"data"];
            NSLog(@"------goodsData = %@",goodsData);
            //获取所有图片数据数据
            [self createBrandListView:goodsData];
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取详情失败"];
    }];
    
}


#pragma mark - 刷新分类数据
-(void)refreshCategoryDate{
    //    NSString * loginName = [NSString stringWithFormat:@"%@",[AppConfig getUserInfoByKey:@"hnLoginName"]];
    //    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
    //    NSLog(@"==param:%@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_CategoryProductType parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取详情失败"];
            return;
        }
        NSLog(@"==dict:%@",data);
        NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *categoryData = [data objectForKey:@"data"];
            NSLog(@"------categoryData = %@",categoryData);
            self.categoryDataSource = categoryData;
            //获取所有图片数据数据
            [self createCategoryView:categoryData];
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
            [self showHint:info];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取详情失败"];
    }];
    
}



@end
